package com.mustafaiev.tair.cts.facade;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dozer.Mapper;

import com.mustafaiev.tair.cts.dao.IBasketDAO;
import com.mustafaiev.tair.cts.exeptions.DataNotRemovedException;
import com.mustafaiev.tair.cts.exeptions.DataNotStoredException;
import com.mustafaiev.tair.cts.model.Basket;
import com.mustafaiev.tair.cts.tapestry.dto.BasketDTO;

/**
 * @author tair
 * 
 */
public class BasketFacade implements IBasketFacade {

	private final IBasketDAO basketDAO;

	private final Mapper mapper;

	private static final Logger LOGGER = Logger.getLogger(BasketFacade.class);

	public BasketFacade(final IBasketDAO basketDAO, final Mapper mapper) {
		this.basketDAO = basketDAO;
		this.mapper = mapper;
	}

	@Override
	public void save(final BasketDTO basketDto) throws DataNotStoredException {
		final Basket basket = this.mapper.map(basketDto, Basket.class);
		this.basketDAO.doSave(basket);
	}

	@Override
	public List<BasketDTO> retrieveBaskets() {
		final List<BasketDTO> basketDtos = new ArrayList<BasketDTO>();
		final List<Basket> baskets = this.basketDAO.retrieveBaskets();
		if (baskets != null) {
			for (final Basket basket : baskets) {
				final BasketDTO basketDto = this.mapper.map(basket,
						BasketDTO.class);
				basketDtos.add(basketDto);
			}
		}
		return basketDtos;
	}

	@Override
	public List<BasketDTO> retrieveNonBatchedBaskets() {
		final List<BasketDTO> basketDtos = new ArrayList<BasketDTO>();
		final List<Basket> baskets = this.basketDAO.retrieveNonBatchedBaskets();
		if (baskets != null) {
			for (final Basket basket : baskets) {
				final BasketDTO basketDto = this.mapper.map(basket,
						BasketDTO.class);
				basketDtos.add(basketDto);
			}
		}
		return basketDtos;
	}

	@Override
	public BasketDTO retrieveBasket(final Long basketId) {
		final BasketDTO basketDto;
		basketDto = this.mapper.map(this.basketDAO.retrieveBasket(basketId),
				BasketDTO.class);
		return basketDto;
	}

	@Override
	public void deleteBatch(final List<BasketDTO> dtos)
			throws DataNotRemovedException {
		final List<Basket> baskets = mapBaskets(dtos);
		try {
			this.basketDAO.deleteBatch(baskets);
		} catch (final DataNotRemovedException e) {
			LOGGER.error(e);
		}
	}

	private List<Basket> mapBaskets(final List<BasketDTO> dtos) {
		final List<Basket> baskets = new ArrayList<Basket>();
		if (dtos != null) {
			for (final BasketDTO basket : dtos) {
				baskets.add(this.mapper.map(basket, Basket.class));
			}
		}
		return baskets;
	}

	@Override
	public void delete(final Long basketId) {
		// TODO Not Implemented

	}

}
